package cn.ccsu.cecs.common.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 拦截器
 */
@Slf4j
public class BaseInterceptor implements HandlerInterceptor {
    private final String attribute;

    public BaseInterceptor(String attribute) {
        this.attribute = attribute;
    }

    /**
     * 校验用户是否登录
     *
     * @param request  请求
     * @param response 响应
     * @param handler  handler
     * @return true or false
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (Objects.isNull(request.getSession().getAttribute(this.attribute))) {
            try {
                // 未登户跳转到网站根目录
                response.sendRedirect("/");
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 拒绝访问
//            log.info("{} 拒绝访问", this.attribute);
            return false;
        }
        // 同意访问
//        log.info("{} 同意访问", this.attribute);
        return true;
    }
}
